#--
#   Television Episode Downloader
#   - Initial Milestone: 4-02-08
#       - Find URL from epguides.com
#       - filenames to rename_list.csv
#   - Internal Milestone 1: 4-05-08
#       - construct new name based on Template
#       - correctly interact with rename_list, make batch/sh/etc and better
#   Rob Dennis - Lurchington Q. Delacroix ESQ. and man about town
#
#   This script is inspired and is thanks to:
#   -   Rob Meerman's tvrenamer perl script
#           http://www.robmeerman.co.uk/coding/file_renamer
#   -   Softpointer's Tag&Rename
#           http://www.softpointer.com/tr
#   
#--

import os,re,glob,time,sys,string,shutil
from string import Template

makeRenameBatchFlag=True
quashBatchEntriesFlag=True
pretendMoveFlag=True
assumeMaxSeasonPlacesFlag=True
episodePlaces=2
episodePadding=2


def renameFileList(inList):
    print "in renameFileList"
    newRows = []

    for row in inList:
        newRow=reshapeName(row)
        newRows.append(newRow)

    if (makeRenameBatchFlag):
        makeRenameBatchFile("renameBatch.sh","mv",newRows,inList)

    for x in range(len(newRows)):
        print "executing: mv",inList[x],newRows[x]
        if not pretendMoveFlag:
            shutil.move(inList[x],newRows[x])

def makeRenameBatchFile(fileName,command,sourceL,destL):
    if len(sourceL) != len(destL):
        print "mismatched rename lists!"
    else:

        if os.path.exists(fileName):
            inF=open(fileName,"rb")

            if not quashBatchEntriesFlag:
                print "---"
                for line in inF.readlines():
                    lineS=line.split()[1:]

                    if (lineS[1] in destL):
                        print lineS[1],"matched, dropping"
                        x=destL.index(lineS[1])
                        destL.pop(x)
                        sourceL.pop(x)

                print "----"
                inF.close()
                modeString="ab"
                
            else:
                modeString="wb"
        else:
            os.system("touch "+fileName)
            
        outF=open(fileName,modeString)
        print "sL:",sourceL
        print "dL:",destL
        for x in range(len(sourceL)):
            outF.write(command+" "+sourceL[x]+" "+destL[x]+"\n")

        outF.close()
            

def reshapeName(oldName,renameString=r"${seriesTitle}_s${seasonNum}_e${episodeNum}"):
##    print "-----"
##    print oldName
##    print "|-->"
##    print renameString

    nameTemplate=Template(renameString)

    print oldName

    series,season,episode,title=searchInfo(oldName)
    extension=oldName[oldName.rfind("."):]

    return nameTemplate.substitute(seriesTitle=series,seasonNum=str(season),episodeNum=str(episode))+extension

def searchInfo(fileN):
#- Getting series title from folder
    seriesRE1=re.compile(r".*(?=(Season))",re.IGNORECASE)

    if seriesRE1.match(os.path.split(sys.path[0])[1]):
        series = seriesRE1.search(os.path.split(sys.path[0])[1]).group(0)
        norm = string.maketrans("","")
        series=series.translate(norm,string.whitespace)
    else:
        print "no series parsed in",os.path.split(sys.path[0])[1]
        series="UNK"
        
#- Getting season number from filename
    seasonRE1=re.compile(r"(?<=[\ _xs\.])[0-9]+",re.IGNORECASE)
    seasonRE2=re.compile(r"^[0-9]+")
    seasonRet="UNK"
    episodeRet="UNK"
    
    if seasonRE1.search(fileN):
        seasonRet=seasonRE1.search(fileN).group(0)
    elif seasonRE2.search(fileN):
        seasonRet=seasonRE2.search(fileN).group(0)
    else:
        print "no season parsed in",fileN

    seasonIndex=fileN.find(seasonRet)+1
    
    if seasonRet != "UNK" and assumeMaxSeasonPlacesFlag:
        if len(seasonRet)>episodePlaces:
            print "splitting season and episode numbers after",episodePlaces
            episodeRet=seasonRet[-episodePlaces:]
            seasonRet=seasonRet[:-episodePlaces]
            
            
#- Getting episode number from filename
    episodeRE1=re.compile(r"(?<=[\ _xe\.])[0-9]+",re.IGNORECASE)
    episodeRE2=re.compile(r"^[0-9]+")

    if episodeRet == "UNK":
        if episodeRE1.search(fileN):
            episodeRet=episodeRE1.search(fileN[seasonIndex:]).group(0)
        elif episodeRE2.search(fileN):
            episodeRet=episodeRE2.search(fileN[seasonIndex:]).group(0)
        else:
            print "no episode parsed in",fileN

    if episodeRet.isdigit():
        episodeRet=episodeRet.zfill(episodePadding)

    return series,seasonRet,episodeRet,""
        
    

    

def main():
    startTime=time.time()
    
    newFileNameList = []
    fileTypes = re.compile(r'.*(avi|mkv)$',re.IGNORECASE)
    fileNameList=glob.glob("*.*")
    for fileN in fileNameList:
        if fileTypes.match(fileN.strip()):
            newFileNameList.append(fileN)

    renameFileList(newFileNameList)

    

    print time.time()-startTime

main()
